package br.edu.infnet.dao;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public abstract class GenericDAO<T> {

	private final static String UNIT_NAME = "infnet";

    @PersistenceContext(unitName = UNIT_NAME)
    private EntityManager em;

    private Class<T> entityClass;

       
    public GenericDAO(Class<T> entityClass) {
    	this.entityClass = entityClass;
    	
    }
	
	
	public void save(T entity) {
		em.persist(entity);
		em.flush();
	}
	
	public void delete(T  entity) {
		em.remove(entity);
		em.flush();
	}
	public T update(T entity) {
		
		T result = em.merge(entity);
		
		em.flush();
		
		return result;
	
	}
	
	public T findById(int entityID) {
		return em.find(entityClass, entityID);
	}
	
	    public List<T> findAll(String q) {
	    	
	    	Query qry = em.createNamedQuery(q);
	    	
	    	return qry.getResultList();
	    }
	   
	    
	    
	 
	 public List<T> ListResultQuery(Query query) {
		 List<T> result = null;
		 
		 result = query.getResultList();
		 
		 return result;
		 
	 }

	 public T OneResultQuery(Query query) {
		 T result = null;
		 
		 result = (T) query.getSingleResult();
		 
		 return result;
		 
	 }


		public EntityManager getEm() {
		return em;
	}


	
	
}
